import Dialog from '../../vant-weapp/dialog/dialog';
import Toast from '../../vant-weapp/toast/toast';
import fw from '../../core/framework.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchTerms: {
      date: '0',
      action: '0',
      person: '0'
    },
    dateData: [
      {
        text: '全部日期',
        value: '0'
      }, {
        text: '指定日期',
        value: '1'
      }
    ],
    actionData: [
      {
        text: '全部动态',
        value: '0'
      }, {
        text: '未处理',
        value: '2'
      }, {
        text: '已处理',
        value: '1'
      }
    ],
    personData: [
      {
        text: '全部人员',
        value: '0'
      }
    ],
    showDate: false,
    minDate: new Date(fw.moment().add(-12, 'month')).getTime(),
    dateTitle:'全部日期',
    defaultDate: fw.moment().format('YYYY/MM/DD'),
    paging: {
      index: 0,
      size: 20,
      totalPages: 0,
      totalElements: 0
    },
    _paging: {
      index: 0,
      size: 20,
      totalPages: 0,
      totalElements: 0
    },
    data: [],
    isLogin: true,
    searchTimer: null,
    searchStatus: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(this.data.minDate)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var self = this;
    this.setData({
      isLogin: fw.user.islogin(),
      paging: fw.clone(self.data._paging)
    });
    if (this.data.isLogin) {
      self.getData();
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (!this.data.isLogin) return false;
    this.setData({
      ['paging.index']: 0
    });
    this.getData();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var _paging = this.data.paging;
    if (_paging.totalElements != 0 && ((_paging.index + 1) * _paging.size > _paging.totalElements)) {
      return false;
    }
    this.setData({
      ['paging.index']: (_paging.index + 1)
    });
    this.getData('search', true);
  },
  search: function (event) {
    let self = this;
    if (!this.data.isLogin) return false;
    if (event) {
      let name = fw.getTargetData(event, 'name');
      let _value = event.detail;
      console.log('search',name,_value)
      if (name == 'date') {
        if(_value == 1){
          self.setData({
            showDate:true,
            ['searchTerms.date']:'1'
          });
          self.selectComponent('#date_drop_item').toggle();
        }else{
          clearTimeout(self.data.searchTimer);
          self.setData({
            searchTimer: (setTimeout(function () {
              self.setData({
                ['searchTerms.date']:'0',
                dateTitle:'全部日期',
                paging: fw.clone(self.data._paging)
              });
              self.getData();
            }, 100))
          })
        }
      } else {
        clearTimeout(self.data.searchTimer);
        self.setData({
          searchTimer: (setTimeout(function () {
            self.setData({
              ['searchTerms.' + name]: _value,
              paging: fw.clone(self.data._paging)
            });
            self.getData('search');
          }, 100))
        })
      }
    } else {
      clearTimeout(self.data.searchTimer);
      self.setData({
        searchTimer: (setTimeout(function () {
          self.setData({
            paging: fw.clone(self.data._paging)
          });
          self.getData();
        }, 100))
      })
    }
  },
  getData(searchStaus, isPaging) {
    let self = this;
    let _paging = self.data.paging;
    let searchTerms = self.data.searchTerms;
    let ajaxOpts = {
      index: _paging.index,
      size: _paging.size
      // date: self.data.searchTerms.date
    };
    if (searchTerms.action != 0) {
      ajaxOpts.handle_type = searchTerms.action | 0;
    }
    if(searchTerms.date == 1){
      ajaxOpts.date = fw.moment(self.data.defaultDate).format('YYYY-MM-DD HH:mm:ss');
    }
    var setSearchStatus = function () {
      self.setData({
        searchStatus: searchStaus == 'search' ? 1 : 2
      });
    };
    fw.ajax('alarmEvent/search', ajaxOpts).then(res => {
      if (res.code == 0) {
        _paging.totalElements = res.data.totalElements;
        self.setData({
          data: self.toUIData(res.data.content, isPaging),
          paging: _paging,
          searchStatus: 0
        });
        if (res.data.content.length == 0) {
          setSearchStatus();
        }
      } else {
        setSearchStatus();
      }
    });
  },
  toUIData(data, isPaging) {
    let self = this;
    let uiData = [];
    let _data = self.data.data;
    let _len = _data.length;
    let len = data.length;
    let itemData = {
      date: null,
      data: []
    };
    if (_len > 0 && isPaging) {
      uiData = fw.clone(_data);
      itemData = _data[_len - 1];
      uiData.pop();
    }
    data.forEach((item, index) => {
      if (itemData.date) {
        if (fw.isSameDay(itemData.date, item.start_time)) {
          itemData.data.push({
            id: item.id,
            text: ((item.face || {}).name || '有人') + '在' + (item.device.name) + '跌倒了',
            type: item.handle_type,
            indexName: item.index_name
          });
          if (index == len - 1) {
            uiData.push(JSON.parse(JSON.stringify(itemData)));
          }
        } else {
          uiData.push(fw.clone(itemData));
          itemData = {
            date: item.start_time,
            data: [
              {
                id: item.id,
                text: ((item.face || {}).name || '有人') + '在' + (item.device.name) + '跌倒了',
                type: item.handle_type,
                indexName: item.index_name
              }
            ]
          }
          if (index == len - 1) {
            uiData.push(fw.clone(itemData));
          }
        }
      } else {
        itemData.date = item.start_time;
        itemData.data.push({
          id: item.id,
          text: ((item.face || {}).name || '有人') + '在' + (item.device.name) + '跌倒了',
          type: item.handle_type,
          indexName: item.index_name
        });
        if (index == len - 1) {
          uiData.push(fw.clone(itemData));
        }
      }
    });
    return uiData;
  },
  openDate() {
    console.log('close item------>',this.data.searchTerms.date)
    if(this.data.searchTerms.date == 1){
      this.setData({
        showDate:true
      })
    }
  },
  closeDate() {
    this.setData({
      showDate: false
    });
    // this.selectComponent('#date_drop_item').toggle();
  },
  confirmDate(event) {
    let date = new Date(event.detail);
    console.log('confirmDate',date);
    let _date = fw.moment(date).format('YYYY-MM-DD');
    this.setData({
      showDate: false,
      defaultDate: _date,
      dateTitle:_date.replace(/-/g,'/')
    });
    this.search();
    this.selectComponent('#date_drop_item').toggle();

  },
  handleDiedao(event) {
    let self = this;
    let data = fw.getTargetData(event, 'data');
    Dialog.confirm({
      title: '报警处理',
      message: '确认已知晓该报警消息，并处理？',
    }).then(() => {
      fw.ajax('alarmEvent/update', { id: data.id, handle_type: 1 }).then(res => {
        if (res.code == 0) {
          self.getData();
        } else {
          Toast.fail(res.msg);
        }
      })
    }).catch(() => {
      // on cancel
    });
  }
})